<template>
  <div class="search-community">
    <el-card>
      <!-- 控制面板 -->
      <el-row flex justify="space-between" style="margin-bottom: 16px">
        <div class="left">
          <el-button type="primary" plain :icon="Plus" @click="newly"
            >添加社区</el-button
          >
          <el-button
            plain
            type="danger"
            :icon="Delete"
            @click="delPatchCommunities"
            >删除</el-button
          >
        </div>
        <div class="right">
          <el-pagination
            v-model:current-page="paginationConfig.currentPage"
            v-model:page-size="paginationConfig.pageSize"
            layout="prev, pager, next"
            :page-count="paginationConfig.pageCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-row>
      <el-scrollbar max-height="600px">
        <el-table
          :data="tableConfig.data"
          border
          stripe
          v-loading="tableConfig.loading"
          element-loading-text="查询中..."
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            min-width="60"
            label="序号"
            prop="id"
          ></el-table-column>
          <el-table-column
            label="社区名称"
            prop="community_name"
            min-width="180"
          ></el-table-column>
          <el-table-column
            label="创建时间"
            prop="created_at"
            min-width="180"
          ></el-table-column>
          <el-table-column label="展示" min-width="150">
            <template #default="scope">
              <el-button
                v-if="!(scope.row.display_url as string).includes('http')"
                size="small"
                @click="handleUpload(scope.row)"
                link
                type="primary"
                >上传图片</el-button
              >
              <el-image
                v-else
                style="width: 100px; height: 100px"
                :src="scope.row.display_url"
                fit="contain"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            prop="updated_at"
            min-width="150"
          ></el-table-column>
          <el-table-column label="操作" min-width="150" fixed="right">
            <template #default="scope">
              <el-popover
                v-if="!(scope.row.display_url as string).includes('http')"
                placement="top-start"
                :width="200"
                trigger="hover"
                content="请先上传图片再进行修改"
              >
                <template #reference>
                  <div>
                    <el-button
                      :disabled="!(scope.row.display_url as string).includes('http')"
                      size="small"
                      link
                      type="warning"
                      :icon="Edit"
                      @click="editCommunity(scope.row)"
                      >编辑</el-button
                    >
                  </div>
                </template>
              </el-popover>
              <el-button
                v-else
                size="small"
                link
                type="warning"
                :icon="Edit"
                @click="editCommunity(scope.row)"
                >编辑</el-button
              >
              <!-- <el-button type="danger" link :icon="Delete" @click="deleteUser(scope.row)">删除</el-button> -->
              <!-- <el-button size="small" link type="success" :icon="View" @click="visible = true">查看</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-card>
    <!-- 添加社区 -->
    <el-dialog
      :title="dialogTitle"
      v-model="visible"
      width="475px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="beforeClose"
    >
      <el-form ref="ruleFormRef" :model="form">
        <el-form-item label="社区名称" prop="name">
          <el-input
            v-model="form.community_name"
            placeholder="长度不超过64个字符"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="展示图片">
          <el-input v-model="form.display_url" disabled></el-input
        ></el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addCommunity(ruleFormRef)"
            >确定</el-button
          >
          <!-- <el-button @click="visible = false">取消</el-button> -->
          <el-button @click="beforeClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传展示图片 -->
    <el-dialog
      :title="uploadDialog.dialogTitle"
      v-model="uploadVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :on-change="handleChange"
        :auto-upload="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽到此处上传或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 500kb
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="uploadVisible = false">取 消</el-button>
          <el-button type="primary" @click="upload(imgFile.content as File)"
            >上 传</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus, Delete, Edit, UploadFilled } from "@element-plus/icons-vue";
import {
  getCommunities,
  createCommunity,
  deleteCommunities,
  updateCommunity,
  getUploadInfo,
  uploadFile,
  downFile,
} from "@/api/community";
import type { FormInstance, UploadFile } from "element-plus";
import { reactive } from "vue";
import { v4 } from "uuid";

// 分页配置信息
const paginationConfig = reactive({
  currentPage: 1,
  pageSize: 30,
  pageCount: 1,
});
// 当分页大小改变
const handleSizeChange = (size: number) => {
  paginationConfig.pageSize = size;
  getCommunityList();
};
// 当页码改变
const handleCurrentChange = (page: number) => {
  paginationConfig.currentPage = page;
  getCommunityList();
};

// 上传图片弹窗
const uploadDialog = reactive({
  dialogTitle: "上传图片",
  uploadVisible: false,
});
const { uploadVisible } = toRefs(uploadDialog);

let imgFile = reactive({
  row: { display_url: "", uuid: "" },
  content: {},
});
// 点击表格中的上传图片
const handleUpload = (row: any) => {
  uploadVisible.value = true;
  imgFile.row = row;
};
// 上传图片
const handleChange = async (uploadFile: UploadFile) => {
  imgFile.content = uploadFile.raw as File;
};
const upload = async (file: File) => {
  if (file !== undefined) {
    const path = `community/${v4()}`;
    const resulut = (await getUploadInfo({ path: path }))?.data;
    if (resulut) {
      let data = new FormData();
      data.append("key", path);
      data.append("Signature", resulut?.authorization);
      data.append("x-cos-security-token", resulut?.token);
      data.append("x-cos-meta-fileid", resulut?.cos_file_id);
      data.append("file", file, path);
      const res = await uploadFile({ url: resulut.url, data: data });
      downFile({
        file_list: [{ fileid: resulut.file_id, max_age: 0 }],
      }).then((res) => {
        console.log("下载图片", res);
        let imgUrl = res.data?.file_list[0]?.download_url;
        imgFile.row.display_url = imgUrl;
        uploadVisible.value = false;
        updateCommunity({
          uuid: imgFile.row.uuid,
          display_url: imgUrl,
        }).then((res) => {
          ElMessage.success("上传成功");
          getCommunityList();
        });
      });
    }
  } else {
    ElMessage.error("上传失败，请重新上传文件");
  }
};

// 弹窗配置
const dialogConfig = reactive({
  dialogTitle: "新增社区",
  visible: false,
});
const { dialogTitle, visible } = toRefs(dialogConfig);

// 小区表格配置信息
const tableConfig = reactive({
  label: "房屋信息",
  loading: true,
  data: [] as any[],
});
// 表单实体
const ruleFormRef = ref<FormInstance>();
// 创建表格
const form = reactive({
  community_name: "",
  display_url: "",
  uuid: "",
});

const multipleSelection = ref([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val.map((item: any) => item.uuid);
};

// 获取小区信息
const getCommunityList = async () => {
  tableConfig.loading = true;
  await getCommunities({
    page: paginationConfig.currentPage,
    num: paginationConfig.pageSize,
  }).then((res) => {
    const data = res.data;
    paginationConfig.pageCount = data?.num_pages ?? 1;
    tableConfig.data = data?.data ?? [];
  });
  tableConfig.loading = false;
  ElMessage.success("查询社区信息成功!");
};
//0表示新增弹窗1表示编辑弹窗

const modalType = ref(0);
const newly = () => {
  modalType.value = 0;
  visible.value = true;
  dialogTitle.value = "新增社区信息";
};

// 新增小区
const addCommunity = (formEl: FormInstance | undefined) => {
  tableConfig.loading = true;
  if (modalType.value === 0) {
    createCommunity({
      community_name: form.community_name,
      display_url: form.display_url,
    })
      .then(async (res) => {
        if (!res) {
          return;
        } else {
          formEl?.resetFields();
          await getCommunityList();
          ElMessage.success("添加成功");
        }
      })
      .catch(() => {
        tableConfig.loading = false;
      });
  } else {
    updateCommunity({
      community_name: form.community_name,
      display_url: form.display_url,
      uuid: form.uuid,
    })
      .then(async () => {
        formEl?.resetFields();
        await getCommunityList();
        ElMessage.success("编辑成功");
      })
      .catch(() => {
        tableConfig.loading = false;
      });
  }
  visible.value = false;
};
// 编辑小区信息
const editCommunity = (row: any) => {
  modalType.value = 1;
  visible.value = true;
  dialogTitle.value = "编辑社区信息";
  form.uuid = row.uuid;
  form.community_name = row.community_name;
  form.display_url = row.display_url;
};
// 批量删除小区
const delPatchCommunities = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请至少选择一个要删除的社区信息",
    });
    return;
  }
  let list = <any>[];
  multipleSelection.value.forEach((e: any) => {
    list.push(e);
  });
  ElMessageBox.confirm("确认删除社区信息?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      tableConfig.loading = true;
      await deleteCommunities({ list });
      await getCommunityList();
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch((err) => {
      if (err) {
        tableConfig.loading = false;
      } else {
        ElMessage({
          type: "info",
          message: "操作取消",
        });
      }
    });
};
// 关闭弹窗
const beforeClose = (done: any) => {
  form.community_name = "";
  form.display_url = "";
  visible.value = false;
  done();
};

onMounted(() => {
  getCommunityList();
});
</script>
<style scoped>
.dialog-footer {
  margin-right: 10px;
}
</style>
